home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / share / pyshared / nevow / athena.py < prev    next >
Text File  |  2007-12-20  |  56KB  |  1,686 lines

  1. # -*- test-case-name: nevow.test.test_athena -*-
  2.  
  3. import itertools, os, re, warnings
  4. from sys import maxint
  5.  
  6. from zope.interface import implements
  7.  
  8. from twisted.internet import defer, error, reactor
  9. from twisted.python import log, failure, context
  10. from twisted.python.util import sibpath
  11. from twisted import plugin
  12.  
  13. from nevow import inevow, plugins, flat
  14. from nevow import rend, loaders, url, static
  15. from nevow import json, util, tags, guard, stan
  16. from nevow.util import CachedFile
  17. from nevow.useragent import UserAgent, browsers
  18.  
  19. from nevow.page import Element, renderer
  20.  
  21. ATHENA_XMLNS_URI = "http://divmod.org/ns/athena/0.7"
  22. ATHENA_RECONNECT = "__athena_reconnect__"
  23.  
  24. expose = util.Expose(
  25.     """
  26.     Allow one or more methods to be invoked by the client::
  27.  
  28.     | class Foo(LiveElement):
  29.     |     def twiddle(self, x, y):
  30.     |         ...
  31.     |     def frob(self, a, b):
  32.     |         ...
  33.     |     expose(twiddle, frob)
  34.  
  35.     The Widget for Foo will be allowed to invoke C{twiddle} and C{frob}.
  36.     """)
  37.  
  38.  
  39.  
  40. class OrphanedFragment(Exception):
  41.     """
  42.     Raised when an operation requiring a parent is attempted on an unattached
  43.     child.
  44.     """
  45.  
  46.  
  47.  
  48. class LivePageError(Exception):
  49.     """
  50.     Base exception for LivePage errors.
  51.     """
  52.     jsClass = u'Divmod.Error'
  53.  
  54.  
  55.  
  56. class NoSuchMethod(LivePageError):
  57.     """
  58.     Raised when an attempt is made to invoke a method which is not defined or
  59.     exposed.
  60.     """
  61.     jsClass = u'Nevow.Athena.NoSuchMethod'
  62.  
  63.     def __init__(self, objectID, methodName):
  64.         self.objectID = objectID
  65.         self.methodName = methodName
  66.         LivePageError.__init__(self, objectID, methodName)
  67.  
  68.  
  69.  
  70. def neverEverCache(request):
  71.     """
  72.     Set headers to indicate that the response to this request should never,
  73.     ever be cached.
  74.     """
  75.     request.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate')
  76.     request.setHeader('Pragma', 'no-cache')
  77.  
  78.  
  79. def activeChannel(request):
  80.     """
  81.     Mark this connection as a 'live' channel by setting the Connection: close
  82.     header and flushing all headers immediately.
  83.     """
  84.     request.setHeader("Connection", "close")
  85.     request.write('')
  86.  
  87.  
  88.  
  89. class JSModules(object):
  90.     """
  91.     Serve implementation files for a JavaScript module system.
  92.  
  93.     @ivar mapping: A C{dict} mapping JavaScript module names (eg,
  94.     'Nevow.Athena') to C{str} instances which name files containing
  95.     JavaScript source implementing those modules.
  96.     """
  97.     implements(inevow.IResource)
  98.  
  99.     def __init__(self, mapping):
  100.         self.mapping = mapping
  101.  
  102.  
  103.     def renderHTTP(self, ctx):
  104.         return rend.FourOhFour()
  105.  
  106.  
  107.     def resourceFactory(self, fileName):
  108.         """
  109.         Retrieve an L{inevow.IResource} which will render the contents of
  110.         C{fileName}.
  111.         """
  112.         return static.File(fileName)
  113.  
  114.  
  115.     def locateChild(self, ctx, segments):
  116.         try:
  117.             impl = self.mapping[segments[0]]
  118.         except KeyError:
  119.             return rend.NotFound
  120.         else:
  121.             return self.resourceFactory(impl), []
  122.  
  123.  
  124.  
  125. # XXX Next two functions copied out of Mantissa/xmantissa/signup.py
  126. def _insertDep(dependent, ordered):
  127.     for dependency in dependent.dependencies():
  128.         _insertDep(dependency, ordered)
  129.     if dependent not in ordered:
  130.         ordered.append(dependent)
  131.  
  132.  
  133.  
  134. def dependencyOrdered(coll):
  135.     ordered = []
  136.     for dependent in coll:
  137.         _insertDep(dependent, ordered)
  138.     return ordered
  139.  
  140.  
  141.  
  142. class JSModule(object):
  143.     _modules = {}
  144.  
  145.     lastModified = 0
  146.     deps = None
  147.     packageDeps = []
  148.  
  149.     def getOrCreate(cls, name, mapping):
  150.         # XXX This implementation of getOrCreate precludes the
  151.         # simultaneous co-existence of several different package
  152.         # namespaces.
  153.         if name in cls._modules:
  154.             return cls._modules[name]
  155.         mod = cls._modules[name] = cls(name, mapping)
  156.         return mod
  157.     getOrCreate = classmethod(getOrCreate)
  158.  
  159.  
  160.     def __init__(self, name, mapping):
  161.         self.name = name
  162.         self.mapping = mapping
  163.  
  164.         if '.' in name:
  165.             parent = '.'.join(name.split('.')[:-1])
  166.             self.packageDeps = [self.getOrCreate(parent, mapping)]
  167.  
  168.         self._cache = CachedFile(self.mapping[self.name], self._getDeps)
  169.  
  170.  
  171.     def __repr__(self):
  172.         return 'JSModule(%r)' % (self.name,)
  173.  
  174.  
  175.     _importExpression = re.compile('^// import (.+)$', re.MULTILINE)
  176.     def _extractImports(self, fileObj):
  177.         s = fileObj.read()
  178.         for m in self._importExpression.finditer(s):
  179.             yield self.getOrCreate(m.group(1).decode('ascii'), self.mapping)
  180.  
  181.  
  182.  
  183.     def _getDeps(self, jsFile):
  184.         """
  185.         Calculate our dependencies given the path to our source.
  186.         """
  187.         depgen = self._extractImports(file(jsFile, 'rU'))
  188.         return self.packageDeps + dict.fromkeys(depgen).keys()
  189.  
  190.  
  191.     def dependencies(self):
  192.         """
  193.         Return a list of names of other JavaScript modules we depend on.
  194.         """
  195.         return self._cache.load()
  196.  
  197.  
  198.     def allDependencies(self):
  199.         if self.mapping[self.name] is None:
  200.             return []
  201.         else:
  202.             mods = [self]
  203.             return dependencyOrdered(mods)
  204.  
  205.  
  206.  
  207. class JSPackage(object):
  208.     implements(plugin.IPlugin, inevow.IJavascriptPackage)
  209.  
  210.     def __init__(self, mapping):
  211.         """
  212.         @param mapping: A C{dict} mapping JS module names to C{str}
  213.         representing filesystem paths containing their
  214.         implementations.
  215.         """
  216.         self.mapping = mapping
  217.  
  218.  
  219. class AutoJSPackage(object):
  220.     """
  221.     An IJavascriptPackage implementation that scans an on-disk hierarchy
  222.     locating modules and packages.
  223.  
  224.     Note that module/package names beginning with . are ignored.
  225.     """
  226.     implements(plugin.IPlugin, inevow.IJavascriptPackage)
  227.  
  228.     def __init__(self, baseDir):
  229.         """
  230.         @param baseDir: A path to the root of a JavaScript packages/modules
  231.         filesystem hierarchy.
  232.         """
  233.         self.mapping = {}
  234.         EMPTY = sibpath(__file__, 'empty.js')
  235.  
  236.         _revMap = {baseDir: ''}
  237.         for root, dirs, filenames in os.walk(baseDir):
  238.             stem = _revMap[root]
  239.             dirs[:] = [d for d in dirs if not d.startswith('.')]
  240.  
  241.             for dir in dirs:
  242.                 name = stem + dir
  243.                 path = os.path.join(root, dir, '__init__.js')
  244.                 if not os.path.exists(path):
  245.                     path = EMPTY
  246.                 self.mapping[unicode(name, 'ascii')] = path
  247.                 _revMap[os.path.join(root, dir)] = name + '.'
  248.  
  249.             for fn in filenames:
  250.                 if fn.startswith('.'):
  251.                     continue
  252.  
  253.                 if fn == '__init__.js':
  254.                     continue
  255.  
  256.                 if fn[-3:] != '.js':
  257.                     continue
  258.  
  259.                 name = stem + fn[:-3]
  260.                 path = os.path.join(root, fn)
  261.                 self.mapping[unicode(name, 'ascii')] = path
  262.  
  263.  
  264.  
  265. def allJavascriptPackages():
  266.     """
  267.     Return a dictionary mapping JavaScript module names to local filenames
  268.     which implement those modules.  This mapping is constructed from all the
  269.     C{IJavascriptPackage} plugins available on the system.  It also includes
  270.     C{Nevow.Athena} as a special case.
  271.     """
  272.     d = {}
  273.     for p in plugin.getPlugIns(inevow.IJavascriptPackage, plugins):
  274.         d.update(p.mapping)
  275.     return d
  276.  
  277.  
  278.  
  279. class JSDependencies(object):
  280.     """
  281.     Keeps track of which JavaScript files depend on which other
  282.     JavaScript files (because JavaScript is a very poor language and
  283.     cannot do this itself).
  284.     """
  285.  
  286.     _loadPlugins = False
  287.  
  288.     def __init__(self, mapping=None):
  289.         if mapping is None:
  290.             self.mapping = {}
  291.             self._loadPlugins = True
  292.         else:
  293.             self.mapping = mapping
  294.  
  295.  
  296.     def getModuleForName(self, className):
  297.         """
  298.         Return the L{JSModule} most likely to define the given name.
  299.         """
  300.         if self._loadPlugins:
  301.             self.mapping.update(allJavascriptPackages())
  302.             self._loadPlugins = False
  303.  
  304.         jsMod = className
  305.         while jsMod:
  306.             try:
  307.                 jsFile = self.mapping[jsMod]
  308.             except KeyError:
  309.                 if '.' not in jsMod:
  310.                     break
  311.                 jsMod = '.'.join(jsMod.split('.')[:-1])
  312.             else:
  313.                 return JSModule.getOrCreate(jsMod, self.mapping)
  314.         raise RuntimeError("Unknown class: %r" % (className,))
  315.     getModuleForClass = getModuleForName
  316.  
  317.  
  318. jsDeps = JSDependencies()
  319.  
  320.  
  321.  
  322. class JSException(Exception):
  323.     """
  324.     Exception class to wrap remote exceptions from JavaScript.
  325.     """
  326.  
  327.  
  328.  
  329. class JSCode(object):
  330.     """
  331.     Class for mock code objects in mock JS frames.
  332.     """
  333.  
  334.     def __init__(self, name, filename):
  335.         self.co_name = name
  336.         self.co_filename = filename
  337.  
  338.  
  339.  
  340. class JSFrame(object):
  341.     """
  342.     Class for mock frame objects in JS client-side traceback wrappers.
  343.     """
  344.  
  345.     def __init__(self, func, fname, ln):
  346.         self.f_back = None
  347.         self.f_locals = {}
  348.         self.f_globals = {}
  349.         self.f_code = JSCode(func, fname)
  350.         self.f_lineno = ln
  351.  
  352.  
  353.  
  354. class JSTraceback(object):
  355.     """
  356.     Class for mock traceback objects representing client-side JavaScript
  357.     tracebacks.
  358.     """
  359.  
  360.     def __init__(self, frame, ln):
  361.         self.tb_frame = frame
  362.         self.tb_lineno = ln
  363.         self.tb_next = None
  364.  
  365.  
  366.  
  367. def parseStack(stack):
  368.     """
  369.     Extract function name, file name, and line number information from the
  370.     string representation of a JavaScript trace-back.
  371.     """
  372.     frames = []
  373.     for line in stack.split('\n'):
  374.         if '@' not in line:
  375.             continue
  376.         func, rest = line.split('@', 1)
  377.         if ':' not in rest:
  378.             continue
  379.  
  380.         divide = rest.rfind(':')
  381.         if divide == -1:
  382.             fname, ln = rest, ''
  383.         else:
  384.             fname, ln = rest[:divide], rest[divide + 1:]
  385.         ln = int(ln)
  386.         frames.insert(0, (func, fname, ln))
  387.     return frames
  388.  
  389. def buildTraceback(frames, modules):
  390.     """
  391.     Build a chain of mock traceback objects from a serialized Error (or other
  392.     exception) object, and return the head of the chain.
  393.     """
  394.     last = None
  395.     first = None
  396.     for func, fname, ln in frames:
  397.         fname = modules.get(fname.split('/')[-1], fname)
  398.         frame = JSFrame(func, fname, ln)
  399.         tb = JSTraceback(frame, ln)
  400.         if last:
  401.             last.tb_next = tb
  402.         else:
  403.             first = tb
  404.         last = tb
  405.     return first
  406.  
  407.  
  408. def getJSFailure(exc, modules):
  409.     """
  410.     Convert a serialized client-side exception to a Failure.
  411.     """
  412.     text = '%s: %s' % (exc[u'name'], exc[u'message'])
  413.  
  414.     frames = []
  415.     if u'stack' in exc:
  416.         frames = parseStack(exc[u'stack'])
  417.  
  418.     return failure.Failure(JSException(text), exc_tb=buildTraceback(frames, modules))
  419.  
  420.  
  421.  
  422. class LivePageTransport(object):
  423.     implements(inevow.IResource)
  424.  
  425.     def __init__(self, messageDeliverer, useActiveChannels=True):
  426.         self.messageDeliverer = messageDeliverer
  427.         self.useActiveChannels = useActiveChannels
  428.  
  429.  
  430.     def locateChild(self, ctx, segments):
  431.         return rend.NotFound
  432.  
  433.  
  434.     def renderHTTP(self, ctx):
  435.         req = inevow.IRequest(ctx)
  436.         neverEverCache(req)
  437.         if self.useActiveChannels:
  438.             activeChannel(req)
  439.  
  440.         requestContent = req.content.read()
  441.         messageData = json.parse(requestContent)
  442.  
  443.         response = self.messageDeliverer.basketCaseReceived(ctx, messageData)
  444.         response.addCallback(json.serialize)
  445.         req.notifyFinish().addErrback(lambda err: self.messageDeliverer._unregisterDeferredAsOutputChannel(response))
  446.         return response
  447.  
  448.  
  449.  
  450. class LivePageFactory:
  451.     noisy = True
  452.  
  453.     def __init__(self):
  454.         self.clients = {}
  455.  
  456.     def addClient(self, client):
  457.         clientID = self._newClientID()
  458.         self.clients[clientID] = client
  459.         if self.noisy:
  460.             log.msg("Rendered new LivePage %r: %r" % (client, clientID))
  461.         return clientID
  462.  
  463.     def getClient(self, clientID):
  464.         return self.clients[clientID]
  465.  
  466.     def removeClient(self, clientID):
  467.         # State-tracking bugs may make it tempting to make the next line a
  468.         # 'pop', but it really shouldn't be; if the Page instance with this
  469.         # client ID is already gone, then it should be gone, which means that
  470.         # this method can't be called with that argument.
  471.         del self.clients[clientID]
  472.         if self.noisy:
  473.             log.msg("Disconnected old LivePage %r" % (clientID,))
  474.  
  475.     def _newClientID(self):
  476.         return guard._sessionCookie()
  477.  
  478.  
  479. _thePrivateAthenaResource = static.File(util.resource_filename('nevow', 'athena_private'))
  480.  
  481.  
  482. class ConnectFailed(Exception):
  483.     pass
  484.  
  485.  
  486. class ConnectionLost(Exception):
  487.     pass
  488.  
  489.  
  490. CLOSE = u'close'
  491. UNLOAD = u'unload'
  492.  
  493. class ReliableMessageDelivery(object):
  494.     _paused = 0
  495.     _stopped = False
  496.  
  497.     outgoingAck = -1            # sequence number which has been acknowledged
  498.                                 # by this end of the connection.
  499.  
  500.     outgoingSeq = -1            # sequence number of the next message to be
  501.                                 # added to the outgoing queue.
  502.  
  503.     def __init__(self,
  504.                  livePage,
  505.                  connectTimeout=60, transportlessTimeout=30, idleTimeout=300,
  506.                  connectionLost=None,
  507.                  scheduler=None):
  508.         self.livePage = livePage
  509.         self.messages = []
  510.         self.outputs = []
  511.         self.connectTimeout = connectTimeout
  512.         self.transportlessTimeout = transportlessTimeout
  513.         self.idleTimeout = idleTimeout
  514.         if scheduler is None:
  515.             scheduler = reactor.callLater
  516.         self.scheduler = scheduler
  517.         self._transportlessTimeoutCall = self.scheduler(self.connectTimeout, self._connectTimedOut)
  518.         self.connectionLost = connectionLost
  519.  
  520.  
  521.     def _connectTimedOut(self):
  522.         self._transportlessTimeoutCall = None
  523.         self.connectionLost(failure.Failure(ConnectFailed("Timeout")))
  524.  
  525.  
  526.     def _transportlessTimedOut(self):
  527.         self._transportlessTimeoutCall = None
  528.         self.connectionLost(failure.Failure(ConnectionLost("Timeout")))
  529.  
  530.  
  531.     def _idleTimedOut(self):
  532.         output, timeout = self.outputs.pop(0)
  533.         if not self.outputs:
  534.             self._transportlessTimeoutCall = self.scheduler(self.transportlessTimeout, self._transportlessTimedOut)
  535.         output([self.outgoingAck, []])
  536.  
  537.  
  538.     def _sendMessagesToOutput(self, output):
  539.         log.msg(athena_send_messages=True, count=len(self.messages))
  540.         output([self.outgoingAck, self.messages])
  541.  
  542.  
  543.     def pause(self):
  544.         self._paused += 1
  545.  
  546.  
  547.     def _trySendMessages(self):
  548.         """
  549.         If we have pending messages and there is an available transport, then
  550.         consume it to send the messages.
  551.         """
  552.         if self.messages and self.outputs:
  553.             output, timeout = self.outputs.pop(0)
  554.             timeout.cancel()
  555.             if not self.outputs:
  556.                 self._transportlessTimeoutCall = self.scheduler(self.transportlessTimeout, self._transportlessTimedOut)
  557.             self._sendMessagesToOutput(output)
  558.  
  559.  
  560.     def unpause(self):
  561.         """
  562.         Decrement the pause counter and if the resulting state is not still
  563.         paused try to flush any pending messages and expend excess outputs.
  564.         """
  565.         self._paused -= 1
  566.         if self._paused == 0:
  567.             self._trySendMessages()
  568.             self._flushOutputs()
  569.  
  570.  
  571.     def addMessage(self, msg):
  572.         if self._stopped:
  573.             return
  574.  
  575.         self.outgoingSeq += 1
  576.         self.messages.append((self.outgoingSeq, msg))
  577.         if not self._paused and self.outputs:
  578.             output, timeout = self.outputs.pop(0)
  579.             timeout.cancel()
  580.             if not self.outputs:
  581.                 self._transportlessTimeoutCall = self.scheduler(self.transportlessTimeout, self._transportlessTimedOut)
  582.             self._sendMessagesToOutput(output)
  583.  
  584.  
  585.     def addOutput(self, output):
  586.         if self._transportlessTimeoutCall is not None:
  587.             self._transportlessTimeoutCall.cancel()
  588.             self._transportlessTimeoutCall = None
  589.         if not self._paused and self.messages:
  590.             self._transportlessTimeoutCall = self.scheduler(self.transportlessTimeout, self._transportlessTimedOut)
  591.             self._sendMessagesToOutput(output)
  592.         else:
  593.             if self._stopped:
  594.                 self._sendMessagesToOutput(output)
  595.             else:
  596.                 self.outputs.append((output, self.scheduler(self.idleTimeout, self._idleTimedOut)))
  597.  
  598.  
  599.     def close(self):
  600.         assert not self._stopped, "Cannot multiply stop ReliableMessageDelivery"
  601.         self.addMessage((CLOSE, []))
  602.         self._stopped = True
  603.         while self.outputs:
  604.             output, timeout = self.outputs.pop(0)
  605.             timeout.cancel()
  606.             self._sendMessagesToOutput(output)
  607.         self.outputs = None
  608.         if self._transportlessTimeoutCall is not None:
  609.             self._transportlessTimeoutCall.cancel()
  610.             self._transportlessTimeoutCall = None
  611.  
  612.  
  613.     def _unregisterDeferredAsOutputChannel(self, deferred):
  614.         for i in xrange(len(self.outputs)):
  615.             if self.outputs[i][0].im_self is deferred:
  616.                 output, timeout = self.outputs.pop(i)
  617.                 timeout.cancel()
  618.                 break
  619.         else:
  620.             return
  621.         if not self.outputs:
  622.             self._transportlessTimeoutCall = self.scheduler(self.transportlessTimeout, self._transportlessTimedOut)
  623.  
  624.  
  625.     def _createOutputDeferred(self):
  626.         """
  627.         Create a new deferred, attaching it as an output.  If the current
  628.         state is not paused, try to flush any pending messages and expend
  629.         any excess outputs.
  630.         """
  631.         d = defer.Deferred()
  632.         self.addOutput(d.callback)
  633.         if not self._paused and self.outputs:
  634.             self._trySendMessages()
  635.             self._flushOutputs()
  636.         return d
  637.  
  638.  
  639.     def _flushOutputs(self):
  640.         """
  641.         Use up all except for one output.
  642.  
  643.         This provides ideal behavior for the default HTTP client
  644.         configuration, since only a maximum of two simultaneous connections
  645.         are allowed.  The remaining one output will let us signal the client
  646.         at will without preventing the client from establishing new
  647.         connections.
  648.         """
  649.         if self.outputs is None:
  650.             return
  651.         while len(self.outputs) > 1:
  652.             output, timeout = self.outputs.pop(0)
  653.             timeout.cancel()
  654.             output([self.outgoingAck, []])
  655.  
  656.  
  657.     def basketCaseReceived(self, ctx, basketCase):
  658.         """
  659.         This is called when some random JSON data is received from an HTTP
  660.         request.
  661.  
  662.         A 'basket case' is currently a data structure of the form [ackNum, [[1,
  663.         message], [2, message], [3, message]]]
  664.  
  665.         Its name is highly informal because unless you are maintaining this
  666.         exact code path, you should not encounter it.  If you do, something has
  667.         gone *badly* wrong.
  668.         """
  669.         ack, incomingMessages = basketCase
  670.  
  671.         outgoingMessages = self.messages
  672.  
  673.         # dequeue messages that our client certainly knows about.
  674.         while outgoingMessages and outgoingMessages[0][0] <= ack:
  675.             outgoingMessages.pop(0)
  676.  
  677.         if incomingMessages:
  678.             log.msg(athena_received_messages=True, count=len(incomingMessages))
  679.             if incomingMessages[0][0] == UNLOAD:
  680.                 # Page-unload messages are special, because they are not part
  681.                 # of the normal message stream: they are a notification that
  682.                 # the message stream can't continue.  Browser bugs force us to
  683.                 # handle this as quickly as possible, since the browser can
  684.                 # lock up hard while waiting for a response to this message
  685.                 # (and the user has already navigated away from the page, so
  686.                 # there's no useful communication that can take place any more)
  687.                 # so only one message is allowed.  In the actual Athena JS,
  688.                 # only one is ever sent, so there is no need to handle more.
  689.                 # The structure of the packet is preserved for symmetry,
  690.                 # however, if we ever need to expand on it.  Realistically, the
  691.                 # only message that can be usefully processed here is CLOSE.
  692.                 msg = incomingMessages[0][1]
  693.                 self.livePage.liveTransportMessageReceived(ctx, msg)
  694.                 return self._createOutputDeferred()
  695.             elif self.outgoingAck + 1 >= incomingMessages[0][0]:
  696.                 lastSentAck = self.outgoingAck
  697.                 self.outgoingAck = max(incomingMessages[-1][0], self.outgoingAck)
  698.                 self.pause()
  699.                 try:
  700.                     for (seq, msg) in incomingMessages:
  701.                         if seq > lastSentAck:
  702.                             self.livePage.liveTransportMessageReceived(ctx, msg)
  703.                         else:
  704.                             log.msg("Athena transport duplicate message, discarding: %r %r" %
  705.                                     (self.livePage.clientID,
  706.                                      seq))
  707.                     d = self._createOutputDeferred()
  708.                 finally:
  709.                     self.unpause()
  710.             else:
  711.                 d = defer.succeed([self.outgoingAck, []])
  712.                 log.msg(
  713.                     "Sequence gap! %r went from %s to %s" %
  714.                     (self.livePage.clientID,
  715.                      self.outgoingAck,
  716.                      incomingMessages[0][0]))
  717.         else:
  718.             d = self._createOutputDeferred()
  719.  
  720.         return d
  721.  
  722.  
  723. BOOTSTRAP_NODE_ID = 'athena:bootstrap'
  724. BOOTSTRAP_STATEMENT = ("eval(document.getElementById('" + BOOTSTRAP_NODE_ID +
  725.                        "').getAttribute('payload'));")
  726.  
  727. class _HasJSClass(object):
  728.     """
  729.     A utility to share some code between the L{LivePage}, L{LiveElement}, and
  730.     L{LiveFragment} classes which all have a jsClass attribute that represents
  731.     a JavaScript class.
  732.  
  733.     @ivar jsClass: a JavaScript class.
  734.     @type jsClass: L{unicode}
  735.     """
  736.  
  737.     def _getModuleForClass(self):
  738.         """
  739.         Get a L{JSModule} object for the class specified by this object's
  740.         jsClass string.
  741.         """
  742.         return jsDeps.getModuleForClass(self.jsClass)
  743.  
  744.  
  745.     def _getRequiredModules(self):
  746.         """
  747.         Return a list of two-tuples containing module names and URLs at which
  748.         those modules are accessible.  All of these modules must be loaded into
  749.         the page before this Fragment's widget can be instantiated.  modules
  750.         are accessible.
  751.         """
  752.         return [
  753.             (dep.name, self.page.getJSModuleURL(dep.name))
  754.             for dep
  755.             in self._getModuleForClass().allDependencies()
  756.             if self.page._shouldInclude(dep.name)]
  757.  
  758.  
  759.  
  760. class LivePage(rend.Page, _HasJSClass):
  761.     """
  762.     A resource which can receive messages from and send messages to the client
  763.     after the initial page load has completed and which can send messages.
  764.  
  765.     @ivar requiredBrowserVersions: A dictionary mapping User-Agent browser
  766.         names to the minimum supported version of those browsers.  Clients
  767.         using these browsers which are below the minimum version will be shown
  768.         an alternate page explaining this rather than the normal page content.
  769.  
  770.     @ivar unsupportedBrowserLoader: A document loader which will be used to
  771.         generate the content shown to unsupported browsers.
  772.     """
  773.  
  774.     jsClass = u'Nevow.Athena.PageWidget'
  775.  
  776.     factory = LivePageFactory()
  777.     _rendered = False
  778.     _didDisconnect = False
  779.  
  780.     useActiveChannels = True
  781.  
  782.     # This is the number of seconds that is acceptable for a LivePage to be
  783.     # considered 'connected' without any transports still active.  In other
  784.     # words, if the browser cannot make requests for more than this timeout
  785.     # (due to network problems, blocking javascript functions, or broken
  786.     # proxies) then deferreds returned from notifyOnDisconnect() will be
  787.     # errbacked with ConnectionLost, and the LivePage will be removed from the
  788.     # factory's cache, and then likely garbage collected.
  789.     TRANSPORTLESS_DISCONNECT_TIMEOUT = 30
  790.  
  791.     # This is the amount of time that each 'transport' request will remain open
  792.     # to the server.  Although the underlying transport, i.e. the conceptual
  793.     # connection established by the sequence of requests, remains alive, it is
  794.     # necessary to periodically cancel requests to avoid browser and proxy
  795.     # bugs.
  796.     TRANSPORT_IDLE_TIMEOUT = 300
  797.  
  798.     page = property(lambda self: self)
  799.  
  800.     # Modules needed to bootstrap
  801.     BOOTSTRAP_MODULES = ['Divmod', 'Divmod.Base', 'Divmod.Defer',
  802.                          'Divmod.Runtime', 'Nevow', 'Nevow.Athena']
  803.  
  804.     # Known minimum working versions of certain browsers.
  805.     requiredBrowserVersions = {
  806.         browsers.GECKO: (20051111,),
  807.         browsers.INTERNET_EXPLORER: (6, 0),
  808.         browsers.WEBKIT: (maxint,),
  809.         browsers.OPERA: (9,)}
  810.  
  811.     unsupportedBrowserLoader = loaders.stan(
  812.         tags.html[
  813.             tags.body[
  814.                 'Your browser is not supported by the Athena toolkit.']])
  815.  
  816.  
  817.     def __init__(self, iface=None, rootObject=None, jsModules=None,
  818.                  jsModuleRoot=None, transportRoot=None, *a, **kw):
  819.         super(LivePage, self).__init__(*a, **kw)
  820.  
  821.         self.iface = iface
  822.         self.rootObject = rootObject
  823.         if jsModules is None:
  824.             jsModules = JSPackage(jsDeps.mapping)
  825.         self.jsModules = jsModules
  826.         self.jsModuleRoot = jsModuleRoot
  827.         if transportRoot is None:
  828.             transportRoot = url.here
  829.         self.transportRoot = transportRoot
  830.         self.liveFragmentChildren = []
  831.         self._includedModules = []
  832.         self._disconnectNotifications = []
  833.  
  834.  
  835.     def _shouldInclude(self, moduleName):
  836.         if moduleName not in self._includedModules:
  837.             self._includedModules.append(moduleName)
  838.             return True
  839.         return False
  840.  
  841.  
  842.     # Child lookup may be dependent on the application state
  843.     # represented by a LivePage.  In this case, it is preferable to
  844.     # dispatch child lookup on the same LivePage instance as performed
  845.     # the initial rendering of the page.  Override the default
  846.     # implementation of locateChild to do this where appropriate.
  847.     def locateChild(self, ctx, segments):
  848.         try:
  849.             client = self.factory.getClient(segments[0])
  850.         except KeyError:
  851.             return super(LivePage, self).locateChild(ctx, segments)
  852.         else:
  853.             return client, segments[1:]
  854.  
  855.  
  856.     def child___athena_private__(self, ctx):
  857.         return _thePrivateAthenaResource
  858.  
  859.  
  860.     # A note on timeout/disconnect logic: whenever a live client goes from some
  861.     # transports to no transports, a timer starts; whenever it goes from no
  862.     # transports to some transports, the timer is stopped; if the timer ever
  863.     # expires the connection is considered lost; every time a transport is
  864.     # added a timer is started; when the transport is used up, the timer is
  865.     # stopped; if the timer ever expires, the transport has a no-op sent down
  866.     # it; if an idle transport is ever disconnected, the connection is
  867.     # considered lost; this lets the server notice clients who actively leave
  868.     # (closed window, browser navigates away) and network congestion/errors
  869.     # (unplugged ethernet cable, etc)
  870.     def _becomeLive(self, location):
  871.         """
  872.         Assign this LivePage a clientID, associate it with a factory, and begin
  873.         tracking its state.  This only occurs when a LivePage is *rendered*,
  874.         not when it is instantiated.
  875.         """
  876.         self.clientID = self.factory.addClient(self)
  877.  
  878.         if self.jsModuleRoot is None:
  879.             self.jsModuleRoot = location.child(self.clientID).child('jsmodule')
  880.  
  881.         self._requestIDCounter = itertools.count().next
  882.  
  883.         self._messageDeliverer = ReliableMessageDelivery(
  884.             self,
  885.             self.TRANSPORTLESS_DISCONNECT_TIMEOUT * 2,
  886.             self.TRANSPORTLESS_DISCONNECT_TIMEOUT,
  887.             self.TRANSPORT_IDLE_TIMEOUT,
  888.             self._disconnected)
  889.         self._remoteCalls = {}
  890.  
  891.         # Mapping of Object-ID to a Python object that will accept messages
  892.         # from the client.
  893.         self._localObjects = {}
  894.  
  895.         # Counter for assigning local object IDs
  896.         self._localObjectIDCounter = itertools.count().next
  897.  
  898.         self.addLocalObject(self)
  899.  
  900.  
  901.     def _supportedBrowser(self, request):
  902.         """
  903.         Determine whether a known-unsupported browser is making a request.
  904.  
  905.         @param request: The L{IRequest} being made.
  906.  
  907.         @rtype: C{bool}
  908.         @return: False if the user agent is known to be unsupported by Athena,
  909.             True otherwise.
  910.         """
  911.         agentString = request.getHeader("user-agent")
  912.         if agentString is None:
  913.             return True
  914.         agent = UserAgent.fromHeaderValue(agentString)
  915.         if agent is None:
  916.             return True
  917.  
  918.         requiredVersion = self.requiredBrowserVersions.get(agent.browser, None)
  919.         if requiredVersion is not None:
  920.             return agent.version >= requiredVersion
  921.         return True
  922.  
  923.  
  924.     def renderUnsupported(self, ctx):
  925.         """
  926.         Render a notification to the user that his user agent is
  927.         unsupported by this LivePage.
  928.  
  929.         @param ctx: The current rendering context.
  930.  
  931.         @return: Something renderable (same behavior as L{renderHTTP})
  932.         """
  933.         return flat.flatten(self.unsupportedBrowserLoader.load())
  934.  
  935.  
  936.     def renderHTTP(self, ctx):
  937.         """
  938.         Attach this livepage to its transport, and render it and all of its
  939.         attached widgets to the browser.  During rendering, the page is
  940.         attached to its factory, acquires a clientID, and has headers set
  941.         appropriately to prevent a browser from ever caching the page, since
  942.         the clientID it gives to the browser is transient and changes every
  943.         time.
  944.  
  945.         These state changes associated with rendering mean that L{LivePage}s
  946.         can only be rendered once, because they are attached to a particular
  947.         user's browser, and it must be unambiguous what browser
  948.         L{LivePage.callRemote} will invoke the method in.
  949.  
  950.         The page's contents are rendered according to its docFactory, as with a
  951.         L{Page}, unless the user-agent requesting this LivePage is determined
  952.         to be unsupported by the JavaScript runtime required by Athena.  In
  953.         that case, a static page is rendered by this page's
  954.         C{renderUnsupported} method.
  955.  
  956.         If a special query argument is set in the URL, "__athena_reconnect__",
  957.         the page will instead render the JSON-encoded clientID by itself as the
  958.         page's content.  This allows an existing live page in a browser to
  959.         programmatically reconnect without re-rendering and re-loading the
  960.         entire page.
  961.  
  962.         @see L{LivePage.renderUnsupported}
  963.  
  964.         @see L{Page.renderHTTP}
  965.  
  966.         @param ctx: a L{WovenContext} with L{IRequest} remembered.
  967.  
  968.         @return: a string (the content of the page) or a Deferred which will
  969.         fire with the same.
  970.  
  971.         @raise RuntimeError: if the page has already been rendered, or this
  972.         page has not been given a factory.
  973.         """
  974.         if self._rendered:
  975.             raise RuntimeError("Cannot render a LivePage more than once")
  976.         if self.factory is None:
  977.             raise RuntimeError("Cannot render a LivePage without a factory")
  978.  
  979.         self._rendered = True
  980.         request = inevow.IRequest(ctx)
  981.         if not self._supportedBrowser(request):
  982.             request.write(self.renderUnsupported(ctx))
  983.             return ''
  984.  
  985.         self._becomeLive(url.URL.fromString(flat.flatten(url.here, ctx)))
  986.  
  987.         neverEverCache(request)
  988.         if request.args.get(ATHENA_RECONNECT):
  989.             return json.serialize(self.clientID.decode("ascii"))
  990.         return rend.Page.renderHTTP(self, ctx)
  991.  
  992.  
  993.     def _disconnected(self, reason):
  994.         if not self._didDisconnect:
  995.             self._didDisconnect = True
  996.  
  997.             notifications = self._disconnectNotifications
  998.             self._disconnectNotifications = None
  999.             for d in notifications:
  1000.                 d.errback(reason)
  1001.             calls = self._remoteCalls
  1002.             self._remoteCalls = {}
  1003.             for (reqID, resD) in calls.iteritems():
  1004.                 resD.errback(reason)
  1005.             self.factory.removeClient(self.clientID)
  1006.  
  1007.  
  1008.     def addLocalObject(self, obj):
  1009.         objID = self._localObjectIDCounter()
  1010.         self._localObjects[objID] = obj
  1011.         return objID
  1012.  
  1013.  
  1014.     def callRemote(self, methodName, *args):
  1015.         requestID = u's2c%i' % (self._requestIDCounter(),)
  1016.         message = (u'call', (unicode(methodName, 'ascii'), requestID, args))
  1017.         resultD = defer.Deferred()
  1018.         self._remoteCalls[requestID] = resultD
  1019.         self.addMessage(message)
  1020.         return resultD
  1021.  
  1022.  
  1023.     def addMessage(self, message):
  1024.         self._messageDeliverer.addMessage(message)
  1025.  
  1026.  
  1027.     def notifyOnDisconnect(self):
  1028.         """
  1029.         Return a Deferred which will fire or errback when this LivePage is
  1030.         no longer connected.
  1031.  
  1032.         Note that if a LivePage never establishes a connection in the first
  1033.         place, the Deferreds this returns will never fire.
  1034.  
  1035.         @rtype: L{defer.Deferred}
  1036.         """
  1037.         d = defer.Deferred()
  1038.         self._disconnectNotifications.append(d)
  1039.         return d
  1040.  
  1041.  
  1042.     def getJSModuleURL(self, moduleName):
  1043.         return self.jsModuleRoot.child(moduleName)
  1044.  
  1045.  
  1046.     def getImportStan(self, moduleName):
  1047.         var = ''
  1048.         if '.' not in moduleName:
  1049.             var = 'var '
  1050.         moduleDef = '%s%s = {};' % (var, moduleName)
  1051.         return [tags.script(type='text/javascript')[tags.raw(moduleDef)],
  1052.                 tags.script(type='text/javascript', src=self.getJSModuleURL(moduleName))]
  1053.  
  1054.  
  1055.     def render_liveglue(self, ctx, data):
  1056.         bootstrapString = '\n'.join(
  1057.             [self._bootstrapCall(method, args) for
  1058.              method, args in self._bootstraps(ctx)])
  1059.         return ctx.tag[
  1060.             # Hit jsDeps.getModuleForName to force it to load some plugins :/
  1061.             # This really needs to be redesigned.
  1062.             [self.getImportStan(jsDeps.getModuleForName(name).name)
  1063.              for (name, url)
  1064.              in self._getRequiredModules()],
  1065.             tags.script(type='text/javascript',
  1066.                         id=BOOTSTRAP_NODE_ID,
  1067.                         payload=bootstrapString)[
  1068.                 BOOTSTRAP_STATEMENT]
  1069.         ]
  1070.  
  1071.  
  1072.     def _bootstraps(self, ctx):
  1073.         """
  1074.         Generate a list of 2-tuples of (methodName, arguments) representing the
  1075.         methods which need to be invoked as soon as all the bootstrap modules
  1076.         are loaded.
  1077.  
  1078.         @param: a L{WovenContext} that can render an URL.
  1079.         """
  1080.         return [
  1081.             ("Divmod.bootstrap",
  1082.              [flat.flatten(self.transportRoot, ctx).decode("ascii")]),
  1083.             ("Nevow.Athena.bootstrap",
  1084.              [self.jsClass, self.clientID.decode('ascii')])]
  1085.  
  1086.  
  1087.     def _bootstrapCall(self, methodName, args):
  1088.         """
  1089.         Generate a string to call a 'bootstrap' function in an Athena JavaScript
  1090.         module client-side.
  1091.  
  1092.         @param methodName: the name of the method.
  1093.  
  1094.         @param args: a list of objects that will be JSON-serialized as
  1095.         arguments to the named method.
  1096.         """
  1097.         return '%s(%s);' % (
  1098.             methodName, ', '.join([json.serialize(arg) for arg in args]))
  1099.  
  1100.  
  1101.     def child_jsmodule(self, ctx):
  1102.         return JSModules(self.jsModules.mapping)
  1103.  
  1104.  
  1105.     _transportResource = None
  1106.     def child_transport(self, ctx):
  1107.         if self._transportResource is None:
  1108.             self._transportResource = LivePageTransport(
  1109.                 self._messageDeliverer,
  1110.                 self.useActiveChannels)
  1111.         return self._transportResource
  1112.  
  1113.  
  1114.     def locateMethod(self, ctx, methodName):
  1115.         if methodName in self.iface:
  1116.             return getattr(self.rootObject, methodName)
  1117.         raise AttributeError(methodName)
  1118.  
  1119.  
  1120.     def liveTransportMessageReceived(self, ctx, (action, args)):
  1121.         """
  1122.         A message was received from the reliable transport layer.  Process it by
  1123.         dispatching it first to myself, then later to application code if
  1124.         applicable.
  1125.         """
  1126.         method = getattr(self, 'action_' + action)
  1127.         method(ctx, *args)
  1128.  
  1129.  
  1130.     def action_call(self, ctx, requestId, method, objectID, args, kwargs):
  1131.         """
  1132.         Handle a remote call initiated by the client.
  1133.         """
  1134.         localObj = self._localObjects[objectID]
  1135.         try:
  1136.             func = localObj.locateMethod(ctx, method)
  1137.         except AttributeError:
  1138.             result = defer.fail(NoSuchMethod(objectID, method))
  1139.         else:
  1140.             result = defer.maybeDeferred(func, *args, **kwargs)
  1141.         def _cbCall(result):
  1142.             success = True
  1143.             if isinstance(result, failure.Failure):
  1144.                 log.msg("Sending error to browser:")
  1145.                 log.err(result)
  1146.                 success = False
  1147.                 if result.check(LivePageError):
  1148.                     result = (
  1149.                         result.value.jsClass,
  1150.                         result.value.args)
  1151.                 else:
  1152.                     result = (
  1153.                         u'Divmod.Error',
  1154.                         [u'%s: %s' % (
  1155.                                 result.type.__name__.decode('ascii'),
  1156.                                 result.getErrorMessage().decode('ascii'))])
  1157.             message = (u'respond', (unicode(requestId), success, result))
  1158.             self.addMessage(message)
  1159.         result.addBoth(_cbCall)
  1160.  
  1161.  
  1162.     def action_respond(self, ctx, responseId, success, result):
  1163.         """
  1164.         Handle the response from the client to a call initiated by the server.
  1165.         """
  1166.         callDeferred = self._remoteCalls.pop(responseId)
  1167.         if success:
  1168.             callDeferred.callback(result)
  1169.         else:
  1170.             callDeferred.errback(getJSFailure(result, self.jsModules.mapping))
  1171.  
  1172.  
  1173.     def action_noop(self, ctx):
  1174.         """
  1175.         Handle noop, used to initialise and ping the live transport.
  1176.         """
  1177.  
  1178.  
  1179.     def action_close(self, ctx):
  1180.         """
  1181.         The client is going away.  Clean up after them.
  1182.         """
  1183.         self._messageDeliverer.close()
  1184.         self._disconnected(error.ConnectionDone("Connection closed"))
  1185.  
  1186.  
  1187.  
  1188. handler = stan.Proto('athena:handler')
  1189. _handlerFormat = "return Nevow.Athena.Widget.handleEvent(this, %(event)s, %(handler)s);"
  1190.  
  1191. def _rewriteEventHandlerToAttribute(tag):
  1192.     """
  1193.     Replace athena:handler children of the given tag with attributes on the tag
  1194.     which correspond to those event handlers.
  1195.     """
  1196.     if isinstance(tag, stan.Tag):
  1197.         extraAttributes = {}
  1198.         for i in xrange(len(tag.children) - 1, -1, -1):
  1199.             if isinstance(tag.children[i], stan.Tag) and tag.children[i].tagName == 'athena:handler':
  1200.                 info = tag.children.pop(i)
  1201.                 name = info.attributes['event'].encode('ascii')
  1202.                 handler = info.attributes['handler']
  1203.                 extraAttributes[name] = _handlerFormat % {
  1204.                     'handler': json.serialize(handler.decode('ascii')),
  1205.                     'event': json.serialize(name.decode('ascii'))}
  1206.                 tag(**extraAttributes)
  1207.     return tag
  1208.  
  1209.  
  1210. def rewriteEventHandlerNodes(root):
  1211.     """
  1212.     Replace all the athena:handler nodes in a given document with onfoo
  1213.     attributes.
  1214.     """
  1215.     stan.visit(root, _rewriteEventHandlerToAttribute)
  1216.     return root
  1217.  
  1218.  
  1219. def _mangleId(oldId):
  1220.     """
  1221.     Return a consistently mangled form of an id that is unique to the widget
  1222.     within which it occurs.
  1223.     """
  1224.     return ['athenaid:', tags.slot('athena:id'), '-', oldId]
  1225.  
  1226.  
  1227. def _rewriteAthenaId(tag):
  1228.     """
  1229.     Rewrite id attributes to be prefixed with the ID of the widget the node is
  1230.     contained by. Also rewrite label "for" attributes which must match the id of
  1231.     their form element.
  1232.     """
  1233.     if isinstance(tag, stan.Tag):
  1234.         elementId = tag.attributes.pop('id', None)
  1235.         if elementId is not None:
  1236.             tag.attributes['id'] = _mangleId(elementId)
  1237.         if tag.tagName == "label":
  1238.             elementFor = tag.attributes.pop('for', None)
  1239.             if elementFor is not None:
  1240.                 tag.attributes['for'] = _mangleId(elementFor)
  1241.         if tag.tagName in ('td', 'th'):
  1242.             headers = tag.attributes.pop('headers', None)
  1243.             if headers is not None:
  1244.                 ids = headers.split()
  1245.                 headers = [_mangleId(headerId) for headerId in ids]
  1246.                 for n in xrange(len(headers) - 1, 0, -1):
  1247.                     headers.insert(n, ' ')
  1248.                 tag.attributes['headers'] = headers
  1249.     return tag
  1250.  
  1251.  
  1252. def rewriteAthenaIds(root):
  1253.     """
  1254.     Rewrite id attributes to be unique to the widget they're in.
  1255.     """
  1256.     stan.visit(root, _rewriteAthenaId)
  1257.     return root
  1258.  
  1259.  
  1260. class _LiveMixin(_HasJSClass):
  1261.     jsClass = u'Nevow.Athena.Widget'
  1262.  
  1263.     preprocessors = [rewriteEventHandlerNodes, rewriteAthenaIds]
  1264.  
  1265.     fragmentParent = None
  1266.  
  1267.     _page = None
  1268.  
  1269.     # Reference to the result of a call to _structured, if one has been made,
  1270.     # otherwise None.  This is used to make _structured() idempotent.
  1271.     _structuredCache = None
  1272.  
  1273.     def __init__(self, *a, **k):
  1274.         super(_LiveMixin, self).__init__(*a, **k)
  1275.         self.liveFragmentChildren = []
  1276.  
  1277.     def page():
  1278.         def get(self):
  1279.             if self._page is None:
  1280.                 if self.fragmentParent is not None:
  1281.                     self._page = self.fragmentParent.page
  1282.             return self._page
  1283.         def set(self, value):
  1284.             self._page = value
  1285.         doc = """
  1286.         The L{LivePage} instance which is the topmost container of this
  1287.         fragment.
  1288.         """
  1289.         return get, set, None, doc
  1290.     page = property(*page())
  1291.  
  1292.  
  1293.     def getInitialArguments(self):
  1294.         """
  1295.         Return a C{tuple} or C{list} of arguments to be passed to this
  1296.         C{LiveFragment}'s client-side Widget.
  1297.  
  1298.         This will be called during the rendering process.  Whatever it
  1299.         returns will be serialized into the page and passed to the
  1300.         C{__init__} method of the widget specified by C{jsClass}.
  1301.  
  1302.         @rtype: C{list} or C{tuple}
  1303.         """
  1304.         return ()
  1305.  
  1306.  
  1307.     def rend(self, context, data):
  1308.         assert isinstance(self.jsClass, unicode), "jsClass must be a unicode string"
  1309.  
  1310.         if self.page is None:
  1311.             raise OrphanedFragment(self)
  1312.         self._athenaID = self.page.addLocalObject(self)
  1313.         context.fillSlots('athena:id', self._athenaID)
  1314.         return super(_LiveMixin, self).rend(context, data)
  1315.  
  1316.  
  1317.     def setFragmentParent(self, fragmentParent):
  1318.         """
  1319.         Sets the L{LiveFragment} (or L{LivePage}) which is the logical parent
  1320.         of this fragment.  This should parallel the client-side hierarchy.
  1321.  
  1322.         All LiveFragments must have setFragmentParent called on them before
  1323.         they are rendered for the client; otherwise, they will be unable to
  1324.         properly hook up to the page.
  1325.  
  1326.         LiveFragments should have their own setFragmentParent called before
  1327.         calling setFragmentParent on any of their own children.  The normal way
  1328.         to accomplish this is to instantiate your fragment children during the
  1329.         render pass.
  1330.  
  1331.         If that isn't feasible, instead override setFragmentParent and
  1332.         instantiate your children there.
  1333.  
  1334.         This architecture might seem contorted, but what it allows that is
  1335.         interesting is adaptation of foreign objects to LiveFragment.  Anywhere
  1336.         you adapt to LiveFragment, setFragmentParent is the next thing that
  1337.         should be called.
  1338.         """
  1339.         self.fragmentParent = fragmentParent
  1340.         self.page = fragmentParent.page
  1341.         fragmentParent.liveFragmentChildren.append(self)
  1342.  
  1343.  
  1344.     def _structured(self):
  1345.         """
  1346.         Retrieve an opaque object which may be usable to construct the
  1347.         client-side Widgets which correspond to this fragment and all of its
  1348.         children.
  1349.         """
  1350.         if self._structuredCache is not None:
  1351.             return self._structuredCache
  1352.  
  1353.         children = []
  1354.         requiredModules = []
  1355.  
  1356.         # Using the context here is terrible but basically necessary given the
  1357.         # /current/ architecture of Athena and flattening.  A better
  1358.         # implementation which was not tied to the rendering system could avoid
  1359.         # this.
  1360.         markup = context.call(
  1361.             {'children': children,
  1362.              'requiredModules': requiredModules},
  1363.             flat.flatten, tags.div(xmlns="http://www.w3.org/1999/xhtml")[self]).decode('utf-8')
  1364.  
  1365.         del children[0]
  1366.  
  1367.         self._structuredCache = {
  1368.             u'requiredModules': [(name, flat.flatten(url).decode('utf-8'))
  1369.                                  for (name, url) in requiredModules],
  1370.             u'class': self.jsClass,
  1371.             u'id': self._athenaID,
  1372.             u'initArguments': tuple(self.getInitialArguments()),
  1373.             u'markup': markup,
  1374.             u'children': children}
  1375.         return self._structuredCache
  1376.  
  1377.  
  1378.     def liveElement(self, request, tag):
  1379.         """
  1380.         Render framework-level boilerplate for making sure the Widget for this
  1381.         Element is created and added to the page properly.
  1382.         """
  1383.         requiredModules = self._getRequiredModules()
  1384.  
  1385.         # Add required attributes to the top widget node
  1386.         tag(**{'xmlns:athena': ATHENA_XMLNS_URI,
  1387.                'id': 'athena:%d' % self._athenaID,
  1388.                'athena:class': self.jsClass})
  1389.  
  1390.         # This will only be set if _structured() is being run.
  1391.         if context.get('children') is not None:
  1392.             context.get('children').append({
  1393.                     u'class': self.jsClass,
  1394.                     u'id': self._athenaID,
  1395.                     u'initArguments': self.getInitialArguments()})
  1396.             context.get('requiredModules').extend(requiredModules)
  1397.             return tag
  1398.  
  1399.         return (
  1400.             # Import stuff
  1401.             [self.getImportStan(name) for (name, url) in requiredModules],
  1402.  
  1403.             # Dump some data for our client-side __init__ into a text area
  1404.             # where it can easily be found.
  1405.             tags.textarea(id='athena-init-args-' + str(self._athenaID),
  1406.                           style="display: none")[
  1407.                 json.serialize(self.getInitialArguments())],
  1408.  
  1409.             # Arrange to be instantiated
  1410.             tags.script(type='text/javascript')[
  1411.                 """
  1412.                 Nevow.Athena.Widget._widgetNodeAdded(%(athenaID)d);
  1413.                 """ % {'athenaID': self._athenaID,
  1414.                        'pythonClass': self.__class__.__name__}],
  1415.  
  1416.             # Okay, application stuff, plus metadata
  1417.             tag,
  1418.             )
  1419.     renderer(liveElement)
  1420.  
  1421.  
  1422.     def render_liveFragment(self, ctx, data):
  1423.         return self.liveElement(inevow.IRequest(ctx), ctx.tag)
  1424.  
  1425.  
  1426.     def getImportStan(self, moduleName):
  1427.         return self.page.getImportStan(moduleName)
  1428.  
  1429.  
  1430.     def locateMethod(self, ctx, methodName):
  1431.         remoteMethod = expose.get(self, methodName, None)
  1432.         if remoteMethod is None:
  1433.             raise AttributeError(self, methodName)
  1434.         return remoteMethod
  1435.  
  1436.  
  1437.     def callRemote(self, methodName, *varargs):
  1438.         return self.page.callRemote(
  1439.             "Nevow.Athena.callByAthenaID",
  1440.             self._athenaID,
  1441.             unicode(methodName, 'ascii'),
  1442.             varargs)
  1443.  
  1444.  
  1445.     def _athenaDetachServer(self):
  1446.         """
  1447.         Locally remove this from its parent.
  1448.  
  1449.         @raise OrphanedFragment: if not attached to a parent.
  1450.         """
  1451.         if self.fragmentParent is None:
  1452.             raise OrphanedFragment(self)
  1453.         for ch in self.liveFragmentChildren:
  1454.             ch._athenaDetachServer()
  1455.         self.fragmentParent.liveFragmentChildren.remove(self)
  1456.         self.fragmentParent = None
  1457.         self.page = None
  1458.         self.detached()
  1459.     expose(_athenaDetachServer)
  1460.  
  1461.  
  1462.     def detach(self):
  1463.         """
  1464.         Remove this from its parent after notifying the client that this is
  1465.         happening.
  1466.  
  1467.         This function will *not* work correctly if the parent/child
  1468.         relationships of this widget do not exactly match the parent/child
  1469.         relationships of the corresponding fragments or elements on the server.
  1470.  
  1471.         @return: A L{Deferred} which will fire when the detach completes.
  1472.         """
  1473.         d = self.callRemote('_athenaDetachClient')
  1474.         d.addCallback(lambda ign: self._athenaDetachServer())
  1475.         return d
  1476.  
  1477.  
  1478.     def detached(self):
  1479.         """
  1480.         Application-level callback invoked when L{detach} succeeds or when the
  1481.         client invokes the detach logic from its side.
  1482.  
  1483.         This is invoked after this fragment has been disassociated from its
  1484.         parent and from the page.
  1485.  
  1486.         Override this.
  1487.         """
  1488.  
  1489.  
  1490.  
  1491. class LiveFragment(_LiveMixin, rend.Fragment):
  1492.     """
  1493.     Base-class for fragments of a LivePage.  When being rendered, a
  1494.     LiveFragment has a special ID attribute added to its top-level
  1495.     tag.  This attribute is used to dispatch calls from the client
  1496.     onto the correct object (this one).
  1497.  
  1498.     A LiveFragment must use the `liveFragment' renderer somewhere in
  1499.     its document template.  The node given this renderer will be the
  1500.     node used to construct a Widget instance in the browser (where it
  1501.     will be saved as the `node' property on the widget object).
  1502.  
  1503.     JavaScript handlers for elements inside this node can use
  1504.     C{Nevow.Athena.Widget.get} to retrieve the widget associated with
  1505.     this LiveFragment.  For example:
  1506.  
  1507.         <form onsubmit="Nevow.Athena.Widget.get(this).callRemote('foo', bar); return false;">
  1508.  
  1509.     Methods of the JavaScript widget class can also be bound as event
  1510.     handlers using the handler tag type in the Athena namespace:
  1511.  
  1512.         <form xmlns:athena="http://divmod.org/ns/athena/0.7">
  1513.             <athena:handler event="onsubmit" handler="doFoo" />
  1514.         </form>
  1515.  
  1516.     This will invoke the C{doFoo} method of the widget which contains the
  1517.     form node.
  1518.  
  1519.     Because this mechanism sets up error handling and otherwise reduces the
  1520.     required boilerplate for handling events, it is preferred and
  1521.     recommended over directly including JavaScript in the event handler
  1522.     attribute of a node.
  1523.  
  1524.     The C{jsClass} attribute of a LiveFragment instance determines the
  1525.     JavaScript class used to construct its corresponding Widget.  This
  1526.     appears as the 'athena:class' attribute.
  1527.  
  1528.     JavaScript modules may import other JavaScript modules by using a
  1529.     special comment which Athena recognizes:
  1530.  
  1531.         // import Module.Name
  1532.  
  1533.     Different imports must be placed on different lines.  No other
  1534.     comment style is supported for these directives.  Only one space
  1535.     character must appear between the string 'import' and the name of
  1536.     the module to be imported.  No trailing whitespace or
  1537.     non-whitespace is allowed.  There must be exactly one space
  1538.     between '//' and 'import'.  There must be no preceeding whitespace
  1539.     on the line.
  1540.  
  1541.     C{Nevow.Athena.Widget.callRemote} can be given permission to invoke methods
  1542.     on L{LiveFragment} instances by passing the functions which implement those
  1543.     methods to L{nevow.athena.expose} in this way::
  1544.  
  1545.         class SomeFragment(LiveFragment):
  1546.             def someMethod(self, ...):
  1547.                 ...
  1548.             expose(someMethod)
  1549.  
  1550.     Only methods exposed in this way will be accessible.
  1551.  
  1552.     L{LiveFragment.callRemote} can be used to invoke any method of the widget
  1553.     on the client.
  1554.  
  1555.     Elements with id attributes will be rewritten so that the id is unique to
  1556.     that particular instance. The client-side C{Nevow.Athena.Widget.nodeById}
  1557.     API is provided to locate these later on. For example:
  1558.  
  1559.         <div id="foo" />
  1560.  
  1561.     and then:
  1562.  
  1563.         var node = self.nodyById('foo');
  1564.  
  1565.     On most platforms, this API will be much faster than similar techniques
  1566.     using C{Nevow.Athena.Widget.nodeByAttribute} etc.
  1567.     """
  1568.     def __init__(self, *a, **kw):
  1569.         super(LiveFragment, self).__init__(*a, **kw)
  1570.         warnings.warn("[v0.10] LiveFragment has been superceded by LiveElement.",
  1571.                       category=PendingDeprecationWarning,
  1572.                       stacklevel=2)
  1573.  
  1574.  
  1575.  
  1576. class LiveElement(_LiveMixin, Element):
  1577.     """
  1578.     Base-class for a portion of a LivePage.  When being rendered, a LiveElement
  1579.     has a special ID attribute added to its top-level tag.  This attribute is
  1580.     used to dispatch calls from the client onto the correct object (this one).
  1581.  
  1582.     A LiveElement must use the `liveElement' renderer somewhere in its document
  1583.     template.  The node given this renderer will be the node used to construct
  1584.     a Widget instance in the browser (where it will be saved as the `node'
  1585.     property on the widget object).
  1586.  
  1587.     JavaScript handlers for elements inside this node can use
  1588.     C{Nevow.Athena.Widget.get} to retrieve the widget associated with this
  1589.     LiveElement.  For example:
  1590.  
  1591.         <form onsubmit="Nevow.Athena.Widget.get(this).callRemote('foo', bar); return false;">
  1592.  
  1593.     Methods of the JavaScript widget class can also be bound as event
  1594.     handlers using the handler tag type in the Athena namespace:
  1595.  
  1596.         <form xmlns:athena="http://divmod.org/ns/athena/0.7">
  1597.             <athena:handler event="onsubmit" handler="doFoo" />
  1598.         </form>
  1599.  
  1600.     This will invoke the C{doFoo} method of the widget which contains the
  1601.     form node.
  1602.  
  1603.     Because this mechanism sets up error handling and otherwise reduces the
  1604.     required boilerplate for handling events, it is preferred and
  1605.     recommended over directly including JavaScript in the event handler
  1606.     attribute of a node.
  1607.  
  1608.     The C{jsClass} attribute of a LiveElement instance determines the
  1609.     JavaScript class used to construct its corresponding Widget.  This appears
  1610.     as the 'athena:class' attribute.
  1611.  
  1612.     JavaScript modules may import other JavaScript modules by using a special
  1613.     comment which Athena recognizes:
  1614.  
  1615.         // import Module.Name
  1616.  
  1617.     Different imports must be placed on different lines.  No other comment
  1618.     style is supported for these directives.  Only one space character must
  1619.     appear between the string 'import' and the name of the module to be
  1620.     imported.  No trailing whitespace or non-whitespace is allowed.  There must
  1621.     be exactly one space between '//' and 'import'.  There must be no
  1622.     preceeding whitespace on the line.
  1623.  
  1624.     C{Nevow.Athena.Widget.callRemote} can be given permission to invoke methods
  1625.     on L{LiveElement} instances by passing the functions which implement those
  1626.     methods to L{nevow.athena.expose} in this way::
  1627.  
  1628.         class SomeElement(LiveElement):
  1629.             def someMethod(self, ...):
  1630.                 ...
  1631.             expose(someMethod)
  1632.  
  1633.     Only methods exposed in this way will be accessible.
  1634.  
  1635.     L{LiveElement.callRemote} can be used to invoke any method of the widget on
  1636.     the client.
  1637.  
  1638.     Elements with id attributes will be rewritten so that the id is unique to
  1639.     that particular instance. The client-side C{Nevow.Athena.Widget.nodeById}
  1640.     API is provided to locate these later on. For example:
  1641.  
  1642.         <div id="foo" />
  1643.  
  1644.     and then:
  1645.  
  1646.         var node = self.nodyById('foo');
  1647.  
  1648.     On most platforms, this API will be much faster than similar techniques
  1649.     using C{Nevow.Athena.Widget.nodeByAttribute} etc.
  1650.     """
  1651.  
  1652.  
  1653. class IntrospectionFragment(LiveFragment):
  1654.     """
  1655.     Utility for developers which provides detailed information about
  1656.     the state of a live page.
  1657.     """
  1658.  
  1659.     jsClass = u'Nevow.Athena.IntrospectionWidget'
  1660.  
  1661.     docFactory = loaders.stan(
  1662.         tags.span(render=tags.directive('liveFragment'))[
  1663.         tags.a(
  1664.         href="#DEBUG_ME",
  1665.         class_='toggle-debug')["Debug"]])
  1666.  
  1667.  
  1668.  
  1669. __all__ = [
  1670.     # Constants
  1671.     'ATHENA_XMLNS_URI',
  1672.  
  1673.     # Errors
  1674.     'LivePageError', 'OrphanedFragment', 'ConnectFailed', 'ConnectionLost'
  1675.  
  1676.     # JS support
  1677.     'JSModules', 'JSModule', 'JSPackage', 'AutoJSPackage', 'allJavascriptPackages',
  1678.     'JSDependencies', 'JSException', 'JSCode', 'JSFrame', 'JSTraceback',
  1679.  
  1680.     # Core objects
  1681.     'LivePage', 'LiveFragment', 'LiveElement', 'IntrospectionFragment',
  1682.  
  1683.     # Decorators
  1684.     'expose', 'handler',
  1685.     ]
  1686.